import { Form, Input, Space, Table } from 'antd';
import type { TableProps } from 'antd/es/table';
import { useEffect, useRef, useState } from 'react';

import deptsApi from '@/api/deptsApi';
import { message, modal } from '@/components/AntdGlobal';
import AuthButton from '@/components/AuthButton';
import SearchForm from '@/components/SearchForm';
import type { IDept } from '@/types/api';
import type { IAction } from '@/types/modal';
import { formatDate } from '@/utils';

import CreateDept from './createDept';

const DeptList = () => {
    /* 数据管理--------------------------------------------------- */
    const [form] = Form.useForm();
    const [dataSource, setDataSource] = useState<IDept.DeptItem[]>([]);
    const deptRef = useRef<{
        openModal: (action: IAction, data?: IDept.EditParams | { parentId: string }) => void;
    }>();
    const columns: TableProps<IDept.DeptItem>['columns'] = [
        {
            title: '部门名称',
            dataIndex: 'deptName',
            key: 'deptName',
            width: 200
        },
        {
            title: '负责人',
            dataIndex: 'userName',
            key: 'userName',
            width: 150
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render(updateTime: string) {
                return formatDate(updateTime);
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render(createTime: string) {
                return formatDate(createTime);
            }
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 200,
            render(_, record: IDept.DeptItem) {
                return (
                    <Space>
                        <AuthButton
                            auth="dept@create"
                            type="primary"
                            onClick={() => handleSubCreate(record.deptId)}
                        >
                            新增
                        </AuthButton>
                        <AuthButton
                            auth="dept@edit"
                            type="primary"
                            onClick={() => handleEdit(record)}
                        >
                            编辑
                        </AuthButton>
                        <AuthButton
                            auth="dept@delete"
                            type="primary"
                            danger
                            onClick={() => handleDelete(record.deptId)}
                        >
                            删除
                        </AuthButton>
                    </Space>
                );
            }
        }
    ];

    /* hooks ---------------------------------------------------- */
    useEffect(() => {
        getAllDeptList();
    }, []);

    /* 函数定义 ---------------------------------------------------*/
    /**获取部门列表
     */
    const getAllDeptList = async () => {
        const values = form.getFieldsValue();
        const { data } = await deptsApi.getDeptsList({
            ...values
        });
        setDataSource(data);
    };

    /**搜索部门列表
     */
    const handleSearch = () => {
        getAllDeptList();
    };

    /**重置表单
     */
    const handleReset = () => {
        form.resetFields();
    };

    /**新增部门
     */
    const handleCreate = () => {
        deptRef.current?.openModal('create');
    };

    /**新增子部门
     */
    const handleSubCreate = (deptId: string) => {
        deptRef.current?.openModal('create', { parentId: deptId });
    };

    /**编辑部门
     */
    const handleEdit = (record: IDept.DeptItem) => {
        deptRef.current?.openModal('edit', record);
    };

    /**删除部门
     */
    const handleDelete = (deptId: string) => {
        modal.confirm({
            title: '确认',
            content: '确认删除该部门吗？',
            onOk() {
                handleExecuteDel(deptId);
            }
        });
    };

    /**执行删除部门
     * @param id
     */
    const handleExecuteDel = async (deptId: string) => {
        await deptsApi.deleteDept({
            deptId
        });
        message.success('删除成功');
        // 更新部门列表
        getAllDeptList();
    };

    return (
        <div className="dept-list">
            <SearchForm
                form={form}
                submit={handleSearch}
                reset={handleReset}
            >
                <Form.Item
                    label="部门名称"
                    name="deptName"
                >
                    <Input
                        placeholder="部门名称"
                        allowClear
                    />
                </Form.Item>
            </SearchForm>
            <div className="base-table">
                <div className="header-wrapper">
                    <div className="title">部门列表</div>
                    <div className="action">
                        <AuthButton
                            auth="dept@create"
                            type="primary"
                            onClick={handleCreate}
                        >
                            新增
                        </AuthButton>
                    </div>
                </div>
                <Table
                    bordered
                    rowKey="deptId"
                    columns={columns}
                    dataSource={dataSource}
                    pagination={false}
                />
            </div>
            <CreateDept
                mRef={deptRef}
                update={getAllDeptList}
            />
        </div>
    );
};

export default DeptList;
